package com.cby.android.library.base

import android.text.TextUtils
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cby.android.library.R
import com.cby.android.library.ext.observe
import com.cby.android.library.ext.showToast
import com.cby.android.library.mvi.PageIntent
import com.cby.android.library.mvi.PageState
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import kotlinx.coroutines.launch


abstract class BasePageStateFragment<VM: BasePageStateViewModel<T>, T>
    : BaseStateFragment<VM, PageState<T>, PageIntent>() {

    private val refreshLayout: RefreshLayout? by lazy { findViewById(R.id.refreshLayout) }
    private val recyclerView: RecyclerView? by lazy { findViewById(R.id.recycler_view) }

    private lateinit var dataAdapter: BaseQuickAdapter<T, BaseViewHolder>

    override fun bindLiveData() {
        observe(viewModel!!.state) {
            refreshLayout?.finishRefresh()
            refreshLayout?.finishLoadMore()
            if(!TextUtils.isEmpty(it.errorMsg)) {
                showToast(it.errorMsg!!)
                return@observe
            }
            if(it.page > 0) {
                dataAdapter.addData(it.list)
            }else{
                dataAdapter.setNewInstance(it.list)
            }

        }
    }

    override fun onViewInit(view: View) {
        dataAdapter = getAdapter()

        addHeaderView(dataAdapter)

        val linearLayoutManager = LinearLayoutManager(activity)
        recyclerView?.apply {
            setHasFixedSize(true)
            layoutManager = linearLayoutManager
            adapter = dataAdapter
            itemAnimator = DefaultItemAnimator()
        }

        refreshLayout?.setOnRefreshListener {
            loadData()
        }

        refreshLayout?.setOnLoadMoreListener {
            loadMoreData()
        }
    }

    override fun loadData() {
        lifecycleScope.launch {
            viewModel!!.intents.send(PageIntent.LoadFirstPageIntent)
        }
    }


    private fun loadMoreData() {
        lifecycleScope.launch {
            viewModel!!.intents.send(PageIntent.LoadMorePageIntent)
        }
    }

    abstract fun getAdapter(): BaseQuickAdapter<T, BaseViewHolder>

    open fun addHeaderView(adapter: BaseQuickAdapter<T,BaseViewHolder>){}

    override fun getLayoutId() = R.layout.common_recycler_view

    override fun getPageTarget() = refreshLayout!!

    override fun reload() {
        loadData()
    }
}